package com.ittx.dzt.jinglyun.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.ittx.dzt.edi.constant.PlatformMessageConstant;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.StoreConfigDTO;
import com.ittx.dzt.edi.vo.ResponseMessageVO;
import com.ittx.dzt.jinglyun.handler.AbstractBaseJinglYunApiHandler;
import com.ittx.dzt.sys.response.Result;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品全量下载
 * <p>
 * cy.sku.all.download
 * /open/api/item/listItems 调用该接口分页查询平台商品信息
 * https://jlopen.jinglyun.com/main/doc?docType=2&cateId=10001&docId=20013
 * </p>
 *
 * @author wl_code@163.com
 * @version 1.0
 * @date 2025/9/1
 */
@Slf4j
@Service
public class JinglYunSkuDownloadAllService extends AbstractBaseJinglYunApiHandler<String> {

	@Override
	public String getJinglMethod() {
		return "/open/api/item/listItems";
	}

	@Override
	public String getLocalApiMethod() {
		return PlatformApiConstant.InboundInterface.SKU_ALL_DOWNLOAD;
	}

	@Override
	public Result<?> doProcess(PlatformApiParamDTO platformApiParamDTO, String paramStr) {
		try {
			StoreConfigDTO storeConfig = platformApiParamDTO.getStoreConfig();
			Map<String, Object> params = new HashMap<>();
			// spuIdList	Array	否	鲸灵内部商品spuId查询条件（Long型数组），给部分需要精确查询场景使用，单次最多10个
			// supplierSpuCodeList	Array	否	供应商商品码查询条件（String型数组），给部分需要精确查询场景使用，单次最多10个
			// pageNo	int	否	分页参数。当前页码，默认值： 1
			// params.put("pageNo", 1);
			// pageSize	int	否	分页参数。每页显示数量，默认值： 5，最大值： 30
			params.put("pageSize", 30);
			Integer total = 0;
			boolean hasNext = true;
			int currentPage = 1;
			do {
				// pageNo	int	否	分页参数。当前页码，默认值： 1
				params.put("pageNo", currentPage);
				Result<?> result = this.executeApi(platformApiParamDTO, params, platformApiParamDTO.getRequestId());
				if (result.hasError()) {
					return result;
				}
				Map<String, Object> resultMap = (Map<String, Object>) result.getData();
				List itemList = MapUtil.get(resultMap, "entry", List.class);
				if (CollUtil.isEmpty(itemList)) {
					String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0017_MSG, platformApiParamDTO.getRequestId(),this.getPlatformCode(), this.getLocalApiMethod());
					return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0017, msg));
				}
				total += itemList.size();
				for (int i = 0; i < itemList.size(); i++) {
					Map<String, Object> skuMap = Convert.toMap(String.class, Object.class, itemList.get(i));
					String itemId = MapUtil.getStr(skuMap, "spuId");
					platformApiParamDTO.setPlatformIdentifierTag(itemId);
					result = this.sendRequestToPlatform(platformApiParamDTO, skuMap, true);
					if (result.hasError()) {
						return result;
					}
				}
				//是否有下一页
				Integer hasNextInt = MapUtil.getInt(resultMap, "hasNext");
				if (hasNextInt == 0) {
					hasNext = false;
				}
				currentPage++; // 增加页码以获取下一页数据
			} while (hasNext);
			return Result.success().addMsg(StrUtil.format("全量商品下载共{}条数据!", total));
		} catch (Exception e) {
			String msg = StrUtil.format(PlatformMessageConstant.MSG_PLAT_0003_MSG, platformApiParamDTO.getRequestId(), this.getPlatformCode(), platformApiParamDTO.getApi(), e.getMessage());
			log.error(msg);
			return Result.error(new ResponseMessageVO(PlatformMessageConstant.MSG_PLAT_0003, msg));
		}
	}
}
